package com.ruoyi.project.bid.controller;

import com.deepoove.poi.xwpf.NiceXWPFDocument;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.config.RuoYiConfig;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.framework.web.page.TableDataInfo;
import com.ruoyi.project.bid.domain.Template;
import com.ruoyi.project.bid.domain.vo.TemplateDetailVO;
import com.ruoyi.project.bid.domain.vo.TemplateMergeVO;
import com.ruoyi.project.bid.domain.vo.TemplateVO;
import com.ruoyi.project.bid.domain.vo.UserDownloadVO;
import com.ruoyi.project.bid.service.ITemplateService;
import com.ruoyi.project.bid.service.IUserDownloadService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.File;
import java.io.FileOutputStream;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.List;

import static com.ruoyi.common.constant.Constants.RESOURCE_PREFIX;

/**
 * 行业模板
 */
@Api(tags = "行业模板")
@RestController
@RequestMapping("/template")
public class TemplateController extends BaseController
{
    @Autowired
    private ITemplateService templateService;
    @Autowired
    private IUserDownloadService userDownloadService;

    /**
     * 获取列表
     */
//    @PreAuthorize("@ss.hasPermi('selfcom:dept:list')")
    @ApiOperation("模板列表")
    @GetMapping("/list")
    public AjaxResult list(Long categoryId)
    {
        Template template = new Template();
        template.setCategoryId(categoryId);
        List<Template> depts = templateService.selectTemplateList(template);
        return AjaxResult.success(depts);
    }

    /**
     * 新增模板
     */
    @ApiOperation("新增模板")
    @PreAuthorize("@ss.hasPermi('selfcom:dept:add')")
    @Log(title = "模板管理", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody TemplateVO dept)
    {
        Template template = new Template();
        template.setCategoryId(dept.getCategoryId());
        template.setTemplateTheme(dept.getTemplateTheme());
        template.setTemplatePath(dept.getTemplatePath());
        template.setCreateBy(SecurityUtils.getUsername());
        return toAjax(templateService.insertTemplate(template));
    }

    @ApiOperation("修改模板")
    @PreAuthorize("@ss.hasPermi('selfcom:dept:edit')")
    @Log(title = "模板管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody TemplateVO dept)
    {
        Template template = new Template();
        template.setCategoryId(dept.getCategoryId());
        template.setTemplateTheme(dept.getTemplateTheme());
        template.setTemplatePath(dept.getTemplatePath());
        template.setUpdateBy(SecurityUtils.getUsername());
        return toAjax(templateService.updateTemplate(template));
    }

    @ApiOperation("删除模板")
    @PreAuthorize("@ss.hasPermi('selfcom:dept:remove')")
    @Log(title = "模板管理", businessType = BusinessType.DELETE)
    @DeleteMapping("/{templateId}")
    public AjaxResult remove(@PathVariable Long templateId)
    {
        return toAjax(templateService.deleteTemplateById(templateId));
    }

    private String toRealPath(String path) {
        return path.replace(RESOURCE_PREFIX, RuoYiConfig.getProfile());
    }

    @ApiOperation("合并模板")
    @Log(title = "合并下载模板", businessType = BusinessType.DOWNLOAD)
    @PostMapping("/merge")
    public void merge(@Valid @Validated @RequestBody TemplateMergeVO templateMergeVO, HttpServletRequest request,
                      HttpServletResponse response) throws Exception {
        List<Template> list = templateService.selectTemplateListByIds(templateMergeVO.getIds());
        String fileName = System.nanoTime() + ".docx";
        String filePath = "./" + fileName;

        // 新文档的地址
        File dest = new File(filePath);
        FileOutputStream out = new FileOutputStream(dest);
        String path = list.get(0).getTemplatePath();
        path = toRealPath(path);
        NiceXWPFDocument mainDoc = new NiceXWPFDocument(Files.newInputStream(Paths.get(path)));
        for (int i = 1; i < list.size(); i++) {
            path = list.get(i).getTemplatePath();
            // 替换资源路径
            path = toRealPath(path);
            NiceXWPFDocument subDoc = new NiceXWPFDocument(Files.newInputStream(Paths.get(path)));
            mainDoc = mainDoc.merge(subDoc);
        }
        mainDoc.write(out);
        mainDoc.close();
        out.close();

        // 保存下载记录
        templateService.insertDownloadRecord(list);

        response.setCharacterEncoding("utf-8");
        response.setContentType("multipart/form-data");
        response.setHeader("Content-Disposition",
                "attachment;fileName=" + FileUtils.setFileDownloadHeader(request, fileName));
        FileUtils.writeBytes(filePath, response.getOutputStream());
    }

    /**
     * 下载统计
     */
    @ApiOperation("下载统计")
    @GetMapping("/overview")
    public TableDataInfo overview(UserDownloadVO userDownloadVO)
    {
        startPage();
        List<UserDownloadVO> list = userDownloadService.selectUserDownloadOverview(userDownloadVO);
        return getDataTable(list);
    }

    /**
     * 下载详情
     */
    @ApiOperation("下载统计详情")
    @GetMapping("/overview/detail")
    public AjaxResult overviewDetail(TemplateDetailVO templateDetailVO)
    {
        List<Template> list = templateService.selectTemplateListByDownload(templateDetailVO);
        return AjaxResult.success(list);
    }
}
